<script setup lang="ts">
import type { RecordList } from '~/types/communications/index'
definePageMeta({
  layout: "chat",
  middleware: 'course'
});
const requestBody = {
  auth: {
    identity: {
      methods: [
        "password"
      ],
      password: {
        user: {
          name: "hw50564198",
          password: "wx991229",
          domain: {
            name: "hw50564198"
          }
        }
      }
    },
    scope: {
      project: {
        name: "cn-southwest-2"
      }
    }
  }
}

// const data = await fetch('https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens', {
//   method: 'post',
//   body: JSON.stringify(requestBody),
//   headers: { 'Content-Type': 'application/json;charset=UTF-8' }
// })
// const token = data.headers.get('x-subject-token')
// 创建语音识别对象


const { isSupported, isListening, isFinal, result, start, stop } = useSpeechRecognition({ lang: 'zh-CN' });
const onStart = () => {
  isListening.value ? start() : onStop
  console.log(isListening.value);
  isListening.value = !isListening.value
}
const onStop = () => {
  stop()
}
const requestBody2 = {
  "Action": "TextToStreamAudio",
  "AppId": 1307962242,
  "Codec": "mp3",
  "Expired": Math.round(Date.now() / 1000) + 60 * 1000 * 60,
  "ModelType": 1,
  "PrimaryLanguage": 1,
  "ProjectId": 0,
  "SampleRate": 16000,
  "SecretId": "AKIDvgCTVIrBG6hmcDZfW8VcWCdojPp0wd4G",
  "SessionId": "123",
  "Speed": 1,
  "Text": "腾讯云语音合成欢迎您。",
  "Timestamp": Math.round(Date.now() / 1000),
  "VoiceType": 101015,
  "Volume": 5
}
const userStore = useUserStore()

const audioTTS = ref('')
const play = (content: string) => {
  const speech = useSpeechSynthesis(content, { lang: 'zh-CN' })
  speech.speak()
}
const state = reactive({
  sendValue: '',
})
const recordList: RecordList = reactive({
  items: [],
})
const getRecordList = computed(() => {
  return [...recordList.items]
})

const messages = ref<Message[]>([])
messages.value.push({ role: 'system', content: '你要作为儿童陪伴AI，名叫小霖霖，主要回答学龄前孩子的问题，以及与孩子日常交流。你应该回复小朋友的问好，亲切的称呼小朋友' })
async function handlerSend() {
  onStop()
  // state.sendValue = state.sendValue.trim()
  result.value = result.value.trim()
  if (!result.value)
    return;
  messages.value.push({ role: 'user', content: result.value })
  recordList.items.push({
    // question: state.sendValue,
    question: result.value,
    delta: { role: 'assistant', content: '' },
    usageTokens: { promptTokens: computeTokens(state.sendValue), completionTokens: 0 },
  })
  document.documentElement.scrollTop = document.body.scrollHeight
  // state.sendValue = ''
  result.value = ''
  await createCompletion(messages.value)
  const indexEnd = recordList.items.length - 1
  messages.value.push({ role: 'assistant', content: recordList.items[indexEnd].delta.content })
  // recordList.items[indexEnd].usageTokens.completionTokens = computeTokens(messages.value[(indexEnd + 1) * 2 - 1].content)
  // play(messages.value[(indexEnd + 1) * 2 - 1].content)
  // const req_url = await getUrl(messages.value[(indexEnd + 1) * 2 - 1].content)
  console.log(messages.value[(indexEnd + 1) * 2].content);
  const ttsData = await getTTS(messages.value[(indexEnd + 1) * 2 ].content)
  // const req_url = main(messages.value[(indexEnd + 1) * 2 - 1].content)
  // const { data } = await useFetch(req_url)
  // console.log("音频", data.value);
  // // @ts-ignore
  // audio.value = data.value.Response.Audio
  audioTTS.value = ttsData

  result.value = ''
}
const getTTS = async (text: string) => {
  const res = await http.get('chat/tts2', { text: text })
  return res.tts
}
export interface Message {
  content: string
  role: 'user' | 'assistant' | 'system'
}
watch(
  () => recordList,
  (val) => {
    if (val)
      document.documentElement.scrollTop = document.body.scrollHeight
  },
  {
    deep: true,
  },
)
const { public: { apiKey } } = useRuntimeConfig()
const errorMessage = ref<string | undefined | unknown>()
async function createCompletion(message: Message[]) {
  try {
    const completion = await fetch('https://api.openai.com/v1/chat/completions', {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`,
      },
      method: 'POST',
      body: JSON.stringify({
        messages: message,
        model: 'gpt-3.5-turbo',
        stream: true,
      }),
    })
      .then((res) => {
        if (res.status === 200)
          return res

        else if (res.status === 401)
          errorMessage.value = '请输入apiKey'

        else if (res.status === 429)
          errorMessage.value = '您超出了当前配额，请检查您的计划和账单明细'

        else if (res.status === 500)
          errorMessage.value = '服务器出错'

        else if (!res.ok)
          errorMessage.value = '请求失败'
      })
      .catch((error) => {
        console.log(error)
      })

    const reader = completion?.body?.getReader()
    if (!reader)
      errorMessage.value = '获取信息失败'
    await read(reader, recordList)
  }
  catch (error) {
    errorMessage.value = `错误${error}`
    console.log('错误', error)
  }
}
async function getUrl(params: string) {
  const res = await http.get('chat/tts', { text: params })
  return res.url
}
// const { sendValue } = toRefs(state)
// watch(() => result.value, () => state.sendValue = result.value)
</script>

<template>
  <div class="px-4 py-3">
    <ul mb-36>
      <div v-for="(item, index) in getRecordList" :key="index" class="px-3 py-2">
        <div class="question mb-2">
          <li
            class="mt-1.5 inline-block max-w-8/10 w-max rounded-lg bg-sky-500 px-3 py-2 align-top text-warm-gray-100 dark:bg-gray-8">
            {{ item.question }}
          </li>
          <div class="ml-1 inline-block h-12 w-12 overflow-hidden border-rd-9 align-top">
            <img :src="userStore.getAvatar" alt="头像" srcset="">
          </div>
          <p class="mr-12 text-xs text-gray-400">
            <!-- <CountTo :start-val="0" :end-val="item.usageTokens.promptTokens" :duration="1000" /> -->
          </p>
        </div>
        <div v-show="!errorMessage">
          <div class="inline-block h-12 w-12 overflow-hidden border-rd-9 align-top">
            <img src="~/assets/svg/chatgpt.svg" alt="chatgpt" srcset="">
          </div>
          <li class="inline-block max-w-8/10 w-max rounded-lg bg-gray-100 px-3 py-2">
            <!-- <MarkdownViewer :value="item.delta.content" /> -->
            {{ item.delta.content }}
          </li>
          <p class="ml-12 text-xs text-gray-400">
            <!-- <CountTo :start-val="0" :end-val="item.usageTokens.completionTokens" :duration="1000" /> -->
          </p>
        </div>
      </div>
      <audio controls autoplay :src="'data:audio/wav;base64,' + audioTTS" />
      <div v-if="errorMessage" class="w-full flex gap-4 border-rd-4 bg-gray-300 p-4 shadow-lg">
        <div class="flex items-center gap-2">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 flex-shrink-0 stroke-current text-red" fill="none"
            viewBox="0 0 24 24" data-v-inspector="pages\index.vue:17:9" data-v-02281a80="">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
              data-v-inspector="pages\index.vue:19:11" data-v-02281a80="" />
          </svg>
          <span class="text-red-500">{{ errorMessage }}</span>
        </div>
      </div>
    </ul>
    <div
      class="childrenPC fixed-bottom mb-10 flex items-center justify-center px-3 py-3 focus:border-width-3 focus:border-yellow-300">
      <textarea v-model="result"
        class="sizeSet input h-12 max-w-8/10 w-full border-width-2 border-gray-500 border-rd px-3 py-2 text-lg outline-yellow-200"
        rows="2" placeholder="请输入您的问题" @keydown.enter.prevent="handlerSend" />
      <button class="ml-1 px-4 py-2 btn" @click="onStart">
        {{ isListening ? '停止' : '语音' }}
      </button>
      <button class="ml-1 px-4 py-2 btn" @click="handlerSend">
        发送
      </button>
    </div>
  </div>
</template>

<style scoped>
.question {
  text-align: right;
}

.childrenPC {
  text-align: center;
}

.fixed-bottom {
  position: fixed;
  bottom: 0;
  width: 100%;
}

.sizeSet {
  resize: none;
}

.input::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.input::-webkit-scrollbar-thumb {
  border-radius: 3px;
  -moz-border-radius: 3px;
  -webkit-border-radius: 3px;
  background-color: #c3c3c3;
}

.input::-webkit-scrollbar-track {
  background-color: transparent;
}
</style>